﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Nop.Core.Log.Model;

namespace Nop.Core.Log
{
    public class StorageTableClientManager
    {
        private static StorageTableClient _client = null;
        private static object _sInternalSyncObject;

        private static object InternalSyncObject
        {
            get
            {
                if (_sInternalSyncObject == null)
                {
                    var o = new Object();
                    Interlocked.CompareExchange(ref _sInternalSyncObject, o, null);
                }
                return _sInternalSyncObject;
            }
        }

        /// <summary>
        /// return StorageTableClient entity
        /// </summary>
        /// <returns></returns>
        public static StorageTableClient GetClient()
        {
            lock (InternalSyncObject)
            {
                if (_client == null)
                {
                    _client = new StorageTableClient(CloudConfigurationManager.GetSetting("StorageConnectionString"))
                    {
                        Client = CloudStorageAccount.Parse(
      CloudConfigurationManager.GetSetting("StorageConnectionString")).CreateCloudTableClient()
                    };

                    Load(_client);
                }

                return _client;
            }
        }

        //init tables
        private static void Load(StorageTableClient client)
        {
            var errorTable = client.Client.GetTableReference("error");
            errorTable.CreateIfNotExists();
            var exceptionTable = client.Client.GetTableReference("exception");
            exceptionTable.CreateIfNotExists();
            var debugTable = client.Client.GetTableReference("debug");
            debugTable.CreateIfNotExists();
            var infoTable = client.Client.GetTableReference("info");
            infoTable.CreateIfNotExists();
        }
    }
}
